import { App, Button, Input, Table, Pagination, Switch, Segmented, SegmentedProps, Select, Spin, Space ,Popconfirm } from 'antd';
import React from 'react';
import { apiInterceptors,getServeUserList,deleteUser,restorePwd,updateUser } from '@/client/api';
import SystemUser from '@/new-components/layout/System';
import { useTranslation } from 'react-i18next';
import { useCallback, useContext, useEffect, useState } from 'react';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import CreateUserModal from './components/addUser'
import AssigningRoles from './components/assigningRoles'
import AssignPermissions from './components/assignPermissions'
import { useDebounceFn, useRequest } from 'ahooks';

type TabKey = 'all' | 'enabled' | 'deactivated';
type ModalType = 'edit' | 'add';

function User() {
  const { t } = useTranslation();
  const items: SegmentedProps['options'] = [
    {
      value: 'all',
      label: t('apps'),
    },
    {
      value: 'enabled',
      label: t('enabled'),
    },
    {
      value: 'deactivated',
      label: t('deactivated'),
    },
  ];
  const [open, setOpen] = useState<boolean>(false); // 新建编辑用户弹框
  const [dataSource, setDataSource] = useState<any>([]); // 新建编辑用户 
  const [openSare, setOpenSare] = useState<boolean>(false); // 分配角色 
  const [openPermissions, setOpenPermissions] = useState<boolean>(false); // 分配角色 
  const [activeKey, setActiveKey] = useState<TabKey>('all');
  const [filterValue, setFilterValue] = useState('');
  const [modalType, setModalType] = useState<ModalType>('add');
  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const { message } = App.useApp();

  const columns = [
    {
      title: t('user_index'),
      dataIndex: 'index',
      key: 'index',
      render: (_, __, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
      width: '5%',
    },
    {
      title: t('user_name'),
      dataIndex: 'login_name',
      key: 'login_name',
      width: '12vw',
    },
    {
      title: t('user_nickname'),
      dataIndex: 'nick_name',
      key: 'nick_name',
      width: '12vw',
    },
    {
      title: t('user_email'),
      dataIndex: 'email',
      key: 'email',
      width: '12vw',
    },
    {
      title: t('user_number'),
      dataIndex: 'telephone',
      key: 'telephone',
      width: '12vw',
    },
    {
      title: t('user_is_active'),
      dataIndex: 'is_active',
      key: 'is_active',
      width: '5%',
      render: (_, record) => (
        <span>
          <Switch  checked={record.is_active === 1} onChange={async (checked) => {
            // const newRecord = { ...record, is_active: checked ? 1 : 0 };
            // setDataSource(dataSource.map(item => item.id === record.id ? newRecord : item))
            const res = await apiInterceptors(updateUser({id:record.id,is_active: checked ? 1 : 0 }));
            if (res[2] && res[2]?.success) {
              checked ? message.success('已启用') : message.success('已停用')
            }
            initData()
          }}/>
        </span>
      ),
    },
    {
      title: t('user_create_datetime'),
      dataIndex: 'create_datetime',
      key: 'create_datetime',
      width: '12vw'
    },
    {
      title: t('user_action'),
      dataIndex: 'action',
      key: 'action',
      width: '12vw',
      render: (_, record) => (
        <div className="flex items-center justify-center">
          <Button
            type='link'
            onClick={() => {
              localStorage.setItem('edit_user_info', JSON.stringify({ ...record, isEdit: true }));
              setModalType('edit');
              setOpen(true);
            }}
          >
            {t('Edit')}
          </Button>
          <Button
            type='link'
            onClick={() => {
              localStorage.setItem('edit_user_info', JSON.stringify({ ...record, isEdit: true  }));
              setOpenSare(true);
            }}
          >
            {t('assigning_roles')}
          </Button>
          <Button
            type='link'
            onClick={async () => {
              localStorage.setItem('edit_user_info', JSON.stringify({ ...record, isEdit: true  }));
              setOpenPermissions(true);
            }}
          >
            {t('assign_permissions')}
          </Button>
          <Popconfirm
            title={t('password_change_prompt')}
            onConfirm={async () => {
              const res = await apiInterceptors(restorePwd({id:record.id}));
              if (res[2] && res[2]?.success) {
                message.success(t('reset_successful'));
              }
            }}
          >
            <Button type='link'>{t('reset_password')}</Button>
          </Popconfirm>
          <Popconfirm
            title={t('want_delete')}
            onConfirm={async () => {
              const res = await apiInterceptors(deleteUser({id:record.id}));
              if (res[2] && res[2]?.success) {
                message.success(t('delete_successful'));
                // 删除后页码修正
                if (dataSource.length === 1 && pagination.current > 1) {
                  setPagination(prev => ({
                    ...prev,
                    current: prev.current - 1
                  }));
                }
              }
              initData()
            }}
          >
            <Button disabled={record.id === 1} type='link'>{t('Delete_Btn')}</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];
  // 获取应用列表
  const { run: initData } = useRequest(
    async () => {
      if (activeKey == 'all') {
        return await getServeUserList({keyword:filterValue});
      }else if (activeKey == 'enabled') {
        return await getServeUserList({keyword:filterValue,is_active:1});
      }else if (activeKey == 'deactivated') {
        return await getServeUserList({keyword:filterValue,is_active:0});
      }else {
        return [];
      }
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const {data} = res.data;
        if (data.items && Array.isArray(data.items)) {
          return setDataSource(data.items)
        }
      },
      debounceWait: 10,
    },
  );

  const handleTabChange = (activeKey: string) => {
    setActiveKey(activeKey as TabKey);
  };
  const onSearch = async (e: any) => {
    const v = e.target.value;
    // 搜索时重置到第一页
    setPagination(prev => ({
      ...prev,
      current: 1
    }));
    setFilterValue(v);
    initData();
  };  
  const handleCreate = () => {
    localStorage.removeItem('edit_user_info');
    setModalType('add');
    setOpen(true);
  };
  const [tableHeight, setTableHeight] = useState('auto');

  const getTableHeight = () => {
    const tHeader = document.querySelector('.ant-table-thead');
    const headerBottom = tHeader?.getBoundingClientRect().bottom || 0;
    const paginationHeight = 64; // 分页器高度
    const extraMargin = 20; // 其他边距
    return `calc(100vh - ${headerBottom + paginationHeight + extraMargin}px)`;
  };
  useEffect(() => {
    setTableHeight(getTableHeight());
    window.addEventListener('resize', () => setTableHeight(getTableHeight()));
    return () => window.removeEventListener('resize', () => {});
  }, []);

  useEffect(() => {
    initData();
  }, [activeKey, initData]);
  
  return (
    <SystemUser>
      <div className='w-full h-full p-4 flex flex-col'>
        <div className='flex justify-between items-center mb-6'>        
          <div className='flex items-center gap-4'>
            <Segmented
              className='backdrop-filter h-10 backdrop-blur-lg bg-white bg-opacity-30 border border-white rounded-lg shadow p-1 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
              options={items as any}
              onChange={handleTabChange}
              value={activeKey}
            />
            <Input
              variant='filled'
              value={filterValue}
              prefix={<SearchOutlined />}
              placeholder={t('please_enter_the_keywords')}
              onChange={onSearch}
              onPressEnter={onSearch}
              allowClear
              className='w-[230px] h-[40px] border-1 border-white backdrop-filter backdrop-blur-lg bg-white bg-opacity-30 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
            />
          </div>
          <Button
            className='border-none text-white bg-button-gradient flex items-center'
            icon={<PlusOutlined className='text-base' />}
            onClick={handleCreate}
          >
            {t('create_user')}
          </Button>
        </div>
        <div className='w-full'>
          <Table 
            tableLayout={'fixed'}
            className='scrollbarStyle'
            dataSource={dataSource} 
            columns={columns}  
            scroll={{ y: tableHeight }}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '50'],
              showTotal: total => `共 ${total} 条`,
              onChange: (page, pageSize) => {
                setPagination({
                  current: page,
                  pageSize,
                  total: pagination.total
                });
                initData();
              }
            }}
          />
        </div>
      </div>
      {open && (
        <CreateUserModal
          open={open}
          onCancel={() => {
            setOpen(false);
            initData()
          }}
          refresh={() => {
            setPagination(prev => ({ ...prev, current: 1 }));
            initData();
          }}
          type={modalType}
        />
      )}
      {openSare && (
        <AssigningRoles
          open={openSare}
          onCancel={() => {
            setOpenSare(false);
          }}
          refresh={() => {
            setPagination(prev => ({ ...prev, current: 1 }));
            initData();
          }}
        />
      )}
      {openPermissions && (
        <AssignPermissions
          open={openPermissions}
          onCancel={() => {
            setOpenPermissions(false);
          }}
          refresh={() => {
            setPagination(prev => ({ ...prev, current: 1 }));
            initData();
          }}
        />
      )}
    </SystemUser>
    
  )
}

export default User;
